import http.client
import json
from comm.module import *
from comm.LogUtils import logger
from comm.postgresutility import postsql_utility

# 获取角色列表
def doGetroleList():
   try:
      logger.info('121:获取角色列表');
      conn = http.client.HTTPSConnection(global_url)
      payload = ''
      headers = {
         'app-id': global_appid,
         'app-key': global_appkey
      }
      conn.request("GET", "/openapi/role/list", payload, headers)
      res = conn.getresponse()
      data = res.read()
      # print(data.decode("utf-8"))
      logger.info('101:' + data.decode("utf-8"))
      conn.close()
   except Exception as e:
      logger.info('121:错误'+str(e));

# 新增或编辑部门接口2
def doSendrole(py_flag,py_no,py_dict):
    try:
        conn = http.client.HTTPSConnection(global_url)
        payload=json.dumps(py_dict)
        headers = {
            'app-id': global_appid,
            'app-key': global_appkey,
            'Content-Type': 'application/json'
        }
        conn.request("POST", "/openapi/role/added", payload, headers)
        res = conn.getresponse()
        data = res.read()
        data = data.decode("utf-8")
        # print(data.decode("utf-8"))
        logger.info('123:' + data)
        conn.close()

        if (py_flag == 2):
            print("修改")
        else:
            # 新增 依据返回值刷新id
            json_str = json.loads(data)
            ierrCode = json_str["errCode"]
            if (ierrCode == 200):
                data_json = json_str["data"]
                id = data_json["id"]
                # print(id, end="\n")
                sql = "update am_sys_role  set update_time=NOW()"
                sql = sql + ",create_id=" + str(id)
                sql = sql + " where id=" + str(py_no) + ";"
                # print(sql)
                conn, cursor = postsql_utility.get_conn()
                i = postsql_utility.execute(sql=sql, cursor=cursor, connect=conn)
                if i != "OK":
                    print("失败" + str(i))
                else:
                    print("成功" + str(i))
    except Exception as e:
        logger.info('123:错误'+str(e));

# 新增或编辑部门接口
def doAddrole():
   try:
      logger.info('122:新增或编辑角色接口');
      # payload = json.dumps({
      #    "id": 55,
      #    "name": "测试员",
      #    "remark": "备注",
      #    "roleCode": "",
      #    "roleLeave": 600,
      #    "sort": 0,
      #    "permissionGroupIdList": [
      #       180,
      #       6
      #    ]
      # })
      sql = "select id,name,description"
      sql = sql +" from am_sys_role"
      sql = sql +" where 1=1"
      sql = sql +" and ((create_id is null) or (create_id=0));"
      logger.info('122:' + sql)
      conn, cursor = postsql_utility.get_conn()
      data = postsql_utility.select(sql=sql, cursor=cursor)

      for j1 in range(len(data)):
          data_dict = {}
          data_dict["name"] = data[j1][1]
          data_dict["remark"] = data[j1][2]
          data_dict["roleCode"] = data[j1][2]
          data_dict["roleLeave"] = 600
          data_dict["sort"] = j1
          #print(data_dict)
          doSendrole(1,data[j1][0],data_dict)

   except Exception as e:
      logger.info('122:错误'+str(e));

#直接调试
#doAddrole()